package com.youfang.sixthmedia.version;

import java.io.File;

import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.RemoteViews;

import com.gzit.common.async.AsynCallback;
import com.gzit.utils.AndroidUtils;
import com.gzit.utils.StringUtils;
import com.youfang.sixthmedia.R;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.message.VersionMessageDelegate;
import com.youfang.sixthmedia.net.Net;
import com.youfang.sixthmedia.net.Pair;
import com.youfang.sixthmedia.net.Response;
import com.youfang.sixthmedia.net.VersionDownloader;

public class VersionService extends Service {

	// apk的MIME值
	public static final String APK_MIME_VALUE = "application/vnd.android.package-archive"; // APK包MIME类型

	// 发现新版本时发送的通知ID
	public static final int FOUND_NEW_VERSION_NOTI_ID = 101;

	// 下载安装包的时候通知的ID
	public static final int DOWNLOAD_NOTI_ID = 102;

	private VersionDownloader versionDownloader;

	private String newVersion;

	private Context context;

	// 是否正在下载中
	private boolean downloading;

	private boolean checkingVersion;

	private String downloadUrl = "";

	/** 检查新版本 **/
	public void checkVersion() {

		if (this.checkingVersion) {
			return;
		}

		this.checkingVersion = true;

		final VersionMessageDelegate delegate = new VersionMessageDelegate();

		Net.simpleMessage(delegate, new AsynCallback<Response>() {

			@Override
			public void callback(Response r) {

				if (r.isFail()) {
					return;
				}

				if (!delegate.resp.needDownload()) {
					stop();
					return;
				}

				downloadUrl = delegate.resp.getDownload();

				sendNewVersionFoundNotification("发现最新版本"
						+ delegate.resp.getVersion() + "是否需要更新?");

			}
		});

	}

	public String getNewVersion() {
		return newVersion;
	}

	public void setNewVersion(String newVersion) {
		this.newVersion = newVersion;
	}

	private void stop() {
		this.stopSelf();

	}

	// ////////////发现新版本，用户确定要下载新版本APK////////////////
	public void downloadNewVersionAPK() {

		if (downloading) {
			versionDownloader.interrupt();
		}

		downloading = true;

		// 1. 准备参数
		String apkUrl = downloadUrl;

		// 2.发起请求
		versionDownloader = new VersionDownloader();
		versionDownloader.setLocalDir(YoufangContext.APP_DIR);
		versionDownloader.setLocalApkFileName("youfang.apk");
		versionDownloader.setUrl(apkUrl).setParams(new Pair[0])
				.setListener(new VersionDownloader.FetcherListener() {

					@Override
					public void onReceive(int total, int received) {
						if (!versionDownloader.isInterrupted()) {
							sendDownloadStatusNotification(total, received);
						}
					}

					@Override
					public void onFinish(File apkFile) {

						downloading = false;
						stop();

						// 下载成功, 安装更新包
						if (!versionDownloader.isInterrupted()) {// 已经中断下载线程则不安装
							Uri uri = Uri.fromFile(apkFile);
							Intent intent = new Intent(Intent.ACTION_VIEW);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.setDataAndType(uri, APK_MIME_VALUE);
							context.startActivity(intent);
						}

					}

					@Override
					public void onError() {
						downloading = false;
						stop();

						// 下载失败
						if (!versionDownloader.isInterrupted()) { // 由于下载被中断掉的错误忽略

						}

					}

					@Override
					public void onInterrupt() {
						downloading = false;
						cancelNotification(DOWNLOAD_NOTI_ID);
						stop();

					}
				}).start();

	}

	/** 终止下载APK包线程 **/
	public void interruptDownload() {
		if (this.versionDownloader != null) {
			this.versionDownloader.interrupt();
		}
	}

	/** APK文件下载进度通知 **/
	public void sendDownloadStatusNotification(int all, int hasRead) {
		float syncRate = ((float) hasRead) / ((float) all) * 100;
		// ////////////////////////////////////////////////////////////////
		if (syncRate >= 100) {
			cancelNotification(DOWNLOAD_NOTI_ID);
			return;
		} else {
			manager = (NotificationManager) context
					.getSystemService(Application.NOTIFICATION_SERVICE);
			view = new RemoteViews(context.getPackageName(),
					R.layout.version_download_progress);
			intent = new Intent(context, VersionDialogActivity.class);
			Bundle bundle = new Bundle();
			bundle.putInt(VersionDialogActivity.INT_KEY_TASK,
					VersionDialogActivity.TASK_DOWNLOAD_ASK);
			bundle.putString(VersionDialogActivity.INT_KEY_CONTENT,
					"正在下载新版本，是否取消？");
			bundle.putString(VersionDialogActivity.INT_KEY_BTN_POSITIVE, "确定");
			bundle.putString(VersionDialogActivity.INT_KEY_BTN_NEGATIVE, "取消");
			intent.putExtras(bundle);
			pIntent = PendingIntent.getActivity(context, 0, intent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			String label = (((int) syncRate) + "%");
			view.setTextViewText(R.id.tv, label);// 关键部分，如果你不重新更新通知，进度条是不会更新的

			notification.icon = R.drawable.ic_launcher;
			notification.tickerText = label;
			notification.contentView = view;
			notification.contentIntent = pIntent;
			manager.notify(DOWNLOAD_NOTI_ID, notification);
			// ////////////////////////////////////////////////////////////////
		}
	}

	// /////////////////////////////////////////////////////

	// 以下对象为状态栏进度条要用
	private RemoteViews view = null;
	private Notification notification = new Notification();
	private NotificationManager manager = null;
	private Intent intent = null;
	private PendingIntent pIntent = null;// 更新显示

	// 发送"发现需要更新的新软件包的通知"
	public void sendNewVersionFoundNotification(String msg) {
		manager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		view = new RemoteViews(context.getPackageName(),
				R.layout.version_update_notify);
		view.setTextViewText(R.id.textNotification, msg);
		intent = new Intent(context, VersionDialogActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt(VersionDialogActivity.INT_KEY_TASK,
				VersionDialogActivity.TASK_CHECK_VERSION);
		bundle.putString(VersionDialogActivity.INT_KEY_CONTENT, msg);
		intent.putExtras(bundle);

		pIntent = PendingIntent.getActivity(context, 0, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		notification.icon = R.drawable.ic_launcher;
		notification.tickerText = msg;
		notification.contentView = view;
		notification.contentIntent = pIntent;
		manager.notify(FOUND_NEW_VERSION_NOTI_ID, notification);
	}

	// /////////////////////////////////////////////////////

	// 取消某个通知
	private void cancelNotification(int notificationId) {
		NotificationManager manager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		manager.cancel(notificationId);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		context = this.getApplicationContext();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		String command = intent.getStringExtra("command");
		if ("start".equals(command)) {
			if (!checkingVersion) {
				if (!downloading) {
					this.checkVersion();
				}
			}

		} else if ("download".equals(command)) {
			String newVersion = intent.getStringExtra("newVersion");
			if (!StringUtils.isStickBlank(newVersion)) {
				this.newVersion = newVersion;
			}

			this.downloadNewVersionAPK();
		} else if ("interrupt".equals(command)) {
			this.interruptDownload();
		}
		return super.onStartCommand(intent, flags, startId);

	}

}